#include "GdfPreCompile.h"
#include "GdfWindow.h"


namespace Gdf
{

	GdfWindowManager* GdfSingleton<GdfWindowManager>::mThis = 0;

	GdfWindowManager::GdfWindowManager()
		:mWindowList()
	{
		InitializeCriticalSection(&mCS);
	}

	GdfWindowManager::~GdfWindowManager()
	{
		EnterCriticalSection(&mCS);
		mWindowList.clear();
		LeaveCriticalSection(&mCS);

		DeleteCriticalSection(&mCS);
	}

	void GdfWindowManager::AddWindow(GdfWindow* window)
	{
		EnterCriticalSection(&mCS);

		if ( mWindowList.end() == std::find( mWindowList.begin(), mWindowList.end(), window ) )
			mWindowList.push_back(window);

		LeaveCriticalSection(&mCS);
	}

	void GdfWindowManager::DeleteWindow(GdfWindow* window)
	{
		EnterCriticalSection(&mCS);

		WindowList::const_iterator it = std::find( mWindowList.begin(), mWindowList.end(), window );
		if ( it != mWindowList.end() )
			mWindowList.erase(it);

		LeaveCriticalSection(&mCS);
	}

	void GdfWindowManager::MessagePump()
	{
		__try
		{
			EnterCriticalSection(&mCS);
			int count = mWindowList.size();
			HWND hwnd;
			MSG msg;
			for ( int i = 0; i < count; ++i )
			{
				hwnd = mWindowList[i]->GetHwnd();
				while ( PeekMessage( &msg, hwnd, 0, 0, PM_REMOVE ) )
				{
					TranslateMessage( &msg );
					DispatchMessage( &msg );
				}
			}
		}
		__finally
		{
			LeaveCriticalSection(&mCS);
		}
	}

	//------------------------------------------------------------------//

	GdfWindow::GdfWindow(HINSTANCE& hInstance)
		:mhInstance(hInstance)
		,mHwnd(0)
	{
	}

	GdfWindow::~GdfWindow()
	{
	}
}
